import {useState, useEffect} from 'react'
import axios from 'axios'
import {throttle} from 'lodash-es'
import './index.css'

export default function Scroll() {
  const [list, setList] = useState([])
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    getData()
    window.addEventListener('scroll', () => {
      scroll()
    })
    window.removeEventListener('scroll', () => {
      scroll()
    })
  }, [])

  function sLoading() {
    return new Promise(resolve => {
      setLoading(true)
      resolve()
    })
  }

  function getData() {
    if (loading) return
    sLoading().then(() => {
      axios('/1.json').then(res => {
        setList(pre => {
          return [...pre, ...res.data]
        })
        setLoading(false)
      })
    })
  }

  const scroll = throttle(() => {
    const scrollHeight = document.body.scrollHeight
    const scrollTop = document.body.scrollTop || document.documentElement.scrollTop
    const clientHeight = document.documentElement.clientHeight
    const distance = scrollHeight - scrollTop - clientHeight
    if (distance < 100) {
      getData()
    }
  }, 300)

  return (
    <div className="box">
      <div className="content-main">这是一段内容</div>
      <div className="content-scroll">
        {
          list.map((item, index) => (
            <div className="scroll-item" key={index}>
              <div className="scroll-item-title">{item.title}</div>
              <div className="scroll-item-main">{item.content}</div>
            </div>
          ))
        }
      </div>
    </div>
  )
}
